package com.example.treehole.activity;


import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.treehole.R;
import com.example.treehole.adapter.GridImageAdapter;
import com.example.treehole.api.Api;
import com.example.treehole.api.ApiConfig;
import com.example.treehole.api.Callback;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.Permission;
import com.luck.picture.lib.permissions.RxPermissions;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.view.listener.OnLvItemClickListener;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

public class PublishActivity extends BaseActivity {


    @BindView(R.id.tv_head_line)
    TextView tvHeadLine;
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.rv_img)
    RecyclerView rvImg;
    @BindView(R.id.rb_public)
    CheckBox rbPublic;

    private List<LocalMedia> selectList = new ArrayList<>();
    private GridImageAdapter adapter;
    private PopupWindow popupWindow;
    private LinearLayout selectLayout;
    private LoadingDialog loadingDialog;

    @Override
    protected int initLayout() {
        return R.layout.activity_publish;
    }

    @Override
    protected void initData() {
        tvHeadLine.setText("心情日记");

        initWidget();

        //准备弹窗
        selectLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.popup_upload_image, null);
        popupWindow = new PopupWindow(selectLayout, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);

    }

    private void initWidget() {
        GridLayoutManager manager = new GridLayoutManager(this, 3);
        rvImg.setLayoutManager(manager);
        selectList.add(0,new LocalMedia());
        adapter = new GridImageAdapter(this,selectList);
        rvImg.setAdapter(adapter);
        adapter.setOnMyItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onClick(int pos) {
                if (selectList.get(pos).getPath()==null) {
                    /*LocalMedia media = selectList.get(pos);
                    showSelect();
                    setBackgroundAlpha(0.7f);*/
                    showDialog();
                }else{
                    jumpTo(getString(R.string.PATH),selectList,pos);
                }
            }
            @Override
            public void onClickCancel(int pos) {
                selectList.remove(pos);
                adapter.notifyDataSetChanged();
            }
        });
        //保存
        //PictureSelector.create(MainActivity.this).externalPicturePreview(position, "/custom_file", selectList);
    }


    @SuppressLint("NonConstantResourceId")
    @OnClick({R.id.iv_exit, R.id.btn_publish})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_exit:
                finish();
                break;
            case R.id.btn_publish:
                insertDynamic();
        }
    }

    private void showDialog() {
        CircleDialog.Builder builder = new CircleDialog.Builder();
        List<String> list = new ArrayList<>();
        list.add("相册选择");
        list.add("拍照");
        builder.setGravity(Gravity.BOTTOM)
                .setWidth(getWindowManager().getDefaultDisplay().getWidth())
                .setItems(list, new OnLvItemClickListener() {
                    @SuppressLint("CheckResult")
                    @Override
                    public boolean onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (position == 0) {
                            PictureSelector.create(PublishActivity.this)
                                    .openGallery(PictureMimeType.ofImage())
                                    .compress(true)
                                    .maxSelectNum(9-selectList.size()+1)
                                    .minSelectNum(1)
                                    .imageSpanCount(3)
                                    .selectionMode(PictureConfig.MULTIPLE)
                                    .forResult(PictureConfig.CHOOSE_REQUEST);
                        } else {
                            //获取写的权限
                            RxPermissions rxPermission = new RxPermissions(PublishActivity.this);
                            rxPermission.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                    .subscribe(new Consumer<Permission>() {
                                        @SuppressLint("CheckResult")
                                        @Override
                                        public void accept(Permission permission) {
                                            if (permission.granted){
                                                PictureSelector.create(PublishActivity.this)
                                                        .openCamera(PictureMimeType.ofImage())
                                                        .compress(true)
                                                        .forResult(PictureConfig.CHOOSE_REQUEST);
                                            }
                                        }
                                    });
                        }
                        return true;
                    }
                })
                .setNegative("取消", null)
                .show(getSupportFragmentManager());
    }
    //遗弃，用新的写法
    /*private void showSelect() {
        popupWindow.showAtLocation(getWindow().getDecorView(),Gravity.BOTTOM,0,0);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1.0f);
            }
        });
        Button btnShoot=selectLayout.findViewById(R.id.btn_shoot);
        Button btnFromAlbum=selectLayout.findViewById(R.id.btn_form_album);
        Button btnCancel=selectLayout.findViewById(R.id.btn_cancel);
        btnShoot.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onClick(View v) {
                //获取写的权限
                RxPermissions rxPermission = new RxPermissions(PublishActivity.this);
                rxPermission.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(new Consumer<Permission>() {
                            @Override
                            public void accept(Permission permission) {
                                if (permission.granted){
                                    PictureSelector.create(PublishActivity.this)
                                            .openCamera(PictureMimeType.ofImage())
                                            .compress(true)
                                            .forResult(PictureConfig.CHOOSE_REQUEST);
                                }
                            }
                        });
            }
        });
        btnFromAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PictureSelector.create(PublishActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .compress(true)
                        .maxSelectNum(9-selectList.size()+1)
                        .minSelectNum(1)
                        .imageSpanCount(3)
                        .selectionMode(PictureConfig.MULTIPLE)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }*/


    @SuppressLint("NotifyDataSetChanged")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> newImages= PictureSelector.obtainMultipleResult(data);
                    selectList.addAll(0,newImages);
                    popupWindow.dismiss();
                    adapter.setData(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }


    private void insertDynamic() {
        String title = etTitle.getText().toString();
        String content = etContent.getText().toString();
        if (content.equals("")) {
            showToast(getString(R.string.input_content));
            return;
        }
        String userId = getStringFromSp("id");
        String[] authors={"温传宝","谢权","王绍启","马一龙"};
        String author=authors[(Integer.parseInt(userId)-4)%4];
        int anonymity = rbPublic.isChecked() ? 0 : 1;
        //准备loading框
        loadingDialog=new LoadingDialog(this);
        loadingDialog.setLoadingText("发布中").show();
        setBackgroundAlpha(0.7f);
        HashMap<String, String> params = new HashMap<>();
        params.put("title", title);
        params.put("text", content);
        params.put("userId", userId);
        params.put("anonymity", anonymity + "");
        params.put("author", author);
        List<File> files=new ArrayList<>();
        for (int i = 0; i < selectList.size() - 1; i++) {
            File file=new File(selectList.get(i).getCompressPath());
            files.add(file);
        }
        Api.config(ApiConfig.POST_DYNAMIC, params).postFile(this,files, new Callback() {
            @Override
            public void onSuccess(String res) {
                if (res.contains("200"))
                    mHandler.sendEmptyMessage(1);
                else
                    mHandler.sendEmptyMessage(2);
            }
            @Override
            public void onFailure(Exception e) {
                e.printStackTrace();
                showToastSync(getString(R.string.check_network));
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what==1){
                loadingDialog.close();
                setResult(200);
                finish();
            }else if (msg.what==2){
                loadingDialog.close();
                showToast("发布失败");
            }
        }
    };

}